#![allow(unused_variables, unused_imports)]
use serde_derive::{Deserialize, Serialize};
use std::io::Write;
use warp::Filter;

mod error;
mod room;

#[derive(Deserialize, Serialize)]
struct Room {
    name: String,
    password: Option<String>,
}

#[tokio::main]
async fn main() {
    tracing_subscriber::fmt::init();

    let html_dir = "../frontend/dist/";
    // let index_html = "./index.html";
    let room_manager = room::RoomManager::new();

    let index = warp::any().and(warp::fs::dir(html_dir));

    let api = warp::path("api");
    // 创建房间
    let room_id = warp::path("room_id");
    let id_router = warp::post()
        .and(api)
        .and(room_id)
        .and(warp::body::content_length_limit(16 * 1024))
        .and(warp::body::json())
        .and(room::with_room_manager(room_manager.clone()))
        .and_then(|user: Room, manager| room::new(user.name, manager, user.password));
    // .and_then(|manager| room::new("hello".into(), manager, None));

    let ws = warp::ws();
    // 这个是加入的时候用的
    // ws://url/meeting/:room_id
    let meeting = ws
        .and(warp::path("meeting"))
        .and(room::with_room_manager(room_manager.clone()))
        .and(warp::path::param::<usize>())
        .map(|ws: warp::ws::Ws, manager, room_id| {
            ws.on_upgrade(move |socket| room::room_ws_handle(room_id, socket, manager))
        });

    let others = warp::get()
        .and(warp::any())
        .and(warp::fs::file(format!("{}index.html", html_dir)));

    let router = index
        .or(id_router)
        .or(meeting)
        .or(others)
        .with(warp::cors().allow_any_origin());

    warp::serve(router).run(([127, 0, 0, 1], 8080)).await;
}
